﻿// Global vars
var FullPriceDataStore;
var FullPriceColumnModel;
var PresidentListingEditorGrid;
var PresidentListingWindow;
var CreateItemForm;
var CreateItemWindow;

var ArticleField;
var LastNameField;

var EnteringOfficeField;
var LeavingOfficeField;
var IncomeField;

var CompanyNameField;

var PresidentListingSelectedRow;
var PresidentListingContextMenu;

/*function RefreshPrice()
{
	$("#dlgRefreshPrices").dialog('open');
	return false;
}*/

Ext.onReady(function(){		
  Ext.QuickTips.init();
  
  // This saves the president after a cell has been edited
  function saveItem(oGrid_event){
   var postVar = oGrid_event.record.data;
   Ext.Ajax.request({   
      waitMsg: 'Please wait...',
      url: 'index.php?module=price&action=saveitem&json=1',
	  params: oGrid_event.record.data,
      success: function(response){              
         var result=eval(response.responseText);
         switch(result){
         case 1:
            FullPriceDataStore.commitChanges();
            FullPriceDataStore.reload();
            break;          
         default:
            Ext.MessageBox.alert('Uh uh...','We couldn\'t save him...');
            break;
         }
      },
      failure: function(response){
         var result=response.responseText;
         Ext.MessageBox.alert('error','could not connect to the database. retry later');    
      }                      
   });   
  }

  // this creates a new president
  function createItem(){
     if(isPresidentFormValid()){
      Ext.Ajax.request({   
        waitMsg: 'Please wait...',
        url: 'index.php?module=price&action=additem&json=1',
        params: {
          article:			ArticleField.getValue(),
          description:		DescriptionField.getValue(),
          companyID:		CompanyNameField.getValue()
          /*enteringoffice: EnteringOfficeField.getValue().format('Y-m-d'),
          leavingoffice:  LeavingOfficeField.getValue().format('Y-m-d'),
          income:          IncomeField.getValue(),
          party:          PartyField.getValue()*/
        }, 
        success: function(response){              
          var result=eval(response.responseText);
          switch(result){
          case 1:
            Ext.MessageBox.alert('Creation OK','The president was created successfully.');
            FullPriceDataStore.reload();
            CreateItemWindow.hide();
            break;
          default:
            Ext.MessageBox.alert('Warning','Could not create the president.');
            break;
          }        
        },
        failure: function(response){
          var result=response.responseText;
          Ext.MessageBox.alert('error','could not connect to the database. retry later');         
        }                      
      });
    } else {
      Ext.MessageBox.alert('Warning', 'Your Form is not valid!');
    }
  }
  
  // reset the Form before opening it
  function resetPresidentForm(){
	ArticleField.setValue('');
	DescriptionField.setValue('');
    /*EnteringOfficeField.setValue('');
    LeavingOfficeField.setValue('');
    IncomeField.setValue('');
    PartyField.setValue('');*/    
  }
  
  // check if the form is valid
  function isPresidentFormValid(){
      return(ArticleField.isValid());
  }
  
  // display or bring forth the form
  function displayFormWindow(){
     if(!CreateItemWindow.isVisible()){
       resetPresidentForm();
       CreateItemWindow.show();
     } else {
       CreateItemWindow.toFront();
     }
  }
  function addItemToCalc()
  {
	  var selections = PresidentListingEditorGrid.selModel.getSelections();
      var prez = [];
      for(i = 0; i< PresidentListingEditorGrid.selModel.getCount(); i++){prez.push(selections[i].json.article);}
      var encoded_array = Ext.encode(prez);
      Ext.Ajax.request({
         waitMsg: 'Please Wait',
         url: 'index.php?module=price&action=addtocalc&json=1', 
         params: { articles:  encoded_array }, 
         success: function(response){
           var result=eval(response.responseText);
           switch(result){
           case 1:  // Success : simply reload
             FullPriceDataStore.reload();
             break;
           default:
             Ext.MessageBox.alert('Warning','Запись не опубликована для кулькулятора');
             break;
           }
         },
         failure: function(response){
           var result=response.responseText;
           Ext.MessageBox.alert('error','Запись не опубликована для кулькулятора');      
           }
      });
  }
  // This was added in Tutorial 6
  function confirmDeleteItem(){
    if(PresidentListingEditorGrid.selModel.getCount() == 1) // only one president is selected here
    {
      Ext.MessageBox.confirm('Подтверждение','Вы действительно хотите удалить запись?', deleteItems);
    } else if(PresidentListingEditorGrid.selModel.getCount() > 1){
      Ext.MessageBox.confirm('Подтверждение','Вы действительно хотите удалить записи?', deleteItems);
    } else {
      Ext.MessageBox.alert('Ошибка','Не выделено ни одной записи.');
    }
  }  
   // This was added in Tutorial 6
  function deleteItems(btn){
    if(btn=='yes'){
         var selections = PresidentListingEditorGrid.selModel.getSelections();
         var prez = [];
         for(i = 0; i< PresidentListingEditorGrid.selModel.getCount(); i++){
          prez.push(selections[i].json.id);
         }
         var encoded_array = Ext.encode(prez);
         Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url: 'index.php?module=price&action=deleteitems&json=1', 
            params: { 
               ids:  encoded_array
              }, 
            success: function(response){
              var result=eval(response.responseText);
              switch(result){
              case 1:  // Success : simply reload
                FullPriceDataStore.reload();
                break;
              default:
                Ext.MessageBox.alert('Warning','Could not delete the entire selection.');
                break;
              }
            },
            failure: function(response){
              var result=response.responseText;
              Ext.MessageBox.alert('error','could not connect to the database. retry later');      
              }
         });
      }  
  }
 
  function startAdvancedSearch(){
      // local vars
      var PresidentSearchForm;
      var PresidentSearchWindow;
      var SearchFirstNameItem;
      var SearchLastNameItem;
      var SearchPartyItem;
      var SearchEnteringItem;
      var SearchLeavingItem;
      
     function listSearch(){
         // render according to a SQL date format.
         var startDate = "";
         var endDate = "";
         if(SearchEnteringItem.getValue() !== "") {
            startDate = SearchEnteringItem.getValue().format('Y-m-d');
         }
         if(SearchLeavingItem.getValue() !== "") {
            endDate = SearchLeavingItem.getValue().format('Y-m-d');
         }
         
         // change the store parameters
        FullPriceDataStore.baseParams = {
         task: 'SEARCH',
         firstname: SearchFirstNameItem.getValue(),
            lastname : SearchLastNameItem.getValue(),
            party : SearchPartyItem.getValue(),
            enteringoffice : startDate,
            leavingoffice : endDate
       };
         // Cause the datastore to do another query : 
       FullPriceDataStore.reload({params: {start: 0, limit: 15}});
     }
     
     function resetSearch(){
         // reset the store parameters
        FullPriceDataStore.baseParams = {
         task: 'LISTING'
       };
         // Cause the datastore to do another query : 
       FullPriceDataStore.reload({params: {start: 0, limit: 15}});
         PresidentSearchWindow.close();
     }
     
      SearchFirstNameItem = new Ext.form.TextField({
          fieldLabel: 'First Name',
          maxLength: 20,
          anchor : '95%',
          maskRe: /([a-zA-Z0-9\s]+)$/
            });

      SearchLastNameItem = new Ext.form.TextField({
          fieldLabel: 'Last Name',
          maxLength: 20,
          anchor : '95%',    
          maskRe: /([a-zA-Z0-9\s]+)$/  
            });
      
      SearchPartyItem = new Ext.form.ComboBox({
         fieldLabel: 'Party',
         store:new Ext.data.SimpleStore({
          fields:['partyValue', 'partyName'],
          data: [['1','No Party'],['2','Federalist'],['3','Democratic-Republican'],['4','Democratic'],['5','Whig'],['6','Republican']]
          }),
         mode: 'local',
         displayField: 'partyName',
         valueField: 'partyValue',
         anchor:'95%',
         triggerAction: 'all'
            });
            
      SearchEnteringItem = new Ext.form.DateField({
          fieldLabel: 'Entered Office after',
          format : 'm/d/Y',
          anchor:'95%'
          });
          
      SearchLeavingItem = new Ext.form.DateField({
          fieldLabel: 'Left Office before',
          format : 'm/d/Y',
          anchor:'95%'
          });
    
     PresidentSearchForm = new Ext.FormPanel({
       //labelAlign: 'top',
       bodyStyle: 'padding: 5px',
       width: 300,
       items: [{
         layout: 'form',
         border: false,
         items: [ SearchFirstNameItem,SearchLastNameItem,SearchPartyItem,SearchEnteringItem, SearchLeavingItem ],
         buttons: [{
               text: 'Search',
               handler: listSearch
             },{
               text: 'Close',
               handler: resetSearch
             }]
         }]
     });
 
     
     PresidentSearchWindow = new Ext.Window({
         title: 'President Search',
         closable:true,
         width: 200,
         height: 400,
         plain:true,
         layout: 'fit',
         items: PresidentSearchForm
     });
 
     
     // once all is done, show the search window
     PresidentSearchWindow.show();
  } 
  
    function printListing(){
      var searchquery = "";
      var searchfirstname = "";
      var searchlastname = "";
      var searchparty = "";
      var searchenteringoffice = "";
      var searchleavingoffice = "";
      var win;               // our popup window
      // check if we do have some search data...
      if(FullPriceDataStore.baseParams.query!==null){searchquery = FullPriceDataStore.baseParams.query;}
      if(FullPriceDataStore.baseParams.firstname!==null){searchfirstname = FullPriceDataStore.baseParams.firstname;}
      if(FullPriceDataStore.baseParams.lastname!==null){searchlastname = FullPriceDataStore.baseParams.lastname;}
      if(FullPriceDataStore.baseParams.party!==null){searchparty = FullPriceDataStore.baseParams.party;}
      if(FullPriceDataStore.baseParams.enteringoffice!==null){searchenteringoffice = FullPriceDataStore.baseParams.enteringoffice;}
      if(FullPriceDataStore.baseParams.leavingoffice!==null){searchleavingoffice = FullPriceDataStore.baseParams.leavingoffice;}
         
      Ext.Ajax.request({   
        waitMsg: 'Please Wait...',
        url: 'database.php',
        params: {
          task: "PRINT",
               // we have to send all of the search

          query: searchquery,                                 // if we are doing a quicksearch, use this
          firstname : searchfirstname,                        // if we are doing advanced search, use this
          lastname : searchlastname,
          party : searchparty,
          enteringoffice : searchenteringoffice,
          leavingoffice : searchleavingoffice,
          currentlisting: FullPriceDataStore.baseParams.task // this tells us if we are searching or not
        }, 
        success: function(response){              
          var result=eval(response.responseText);
          switch(result){
          case 1:
            win = window.open('./presidentslist.html','presidentslist','height=400,width=600,resizable=1,scrollbars=1, menubar=1');
            win.print();
            break;
          default:
            Ext.MessageBox.alert('Uh hu...','Unable to print the grid!');
            break;
          }  
        },
        failure: function(response){
          var result=response.responseText;
          Ext.MessageBox.alert('error','could not connect to the database. retry later');      
        }                      
      });
  }
 
  function onPresidentListingEditorGridContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    PresidentListingContextMenu.rowRecord = grid.store.getAt(rowIndex);
    grid.selModel.selectRow(rowIndex);
    PresidentListingSelectedRow=rowIndex;
    PresidentListingContextMenu.showAt([coords[0], coords[1]]);
  }
 
  function modifyPresidentContextMenu(){
      PresidentListingEditorGrid.startEditing(PresidentListingSelectedRow,1);
  }

  function deletePresidentContextMenu(){
      confirmDeleteItem();
  }

  function printListingContextMenu(){
      printListing();
  }

  
  // << CONFIG >>
  FullPriceDataStore = new Ext.data.Store({
      id: 'FullPriceDataStore',
      proxy: new Ext.data.HttpProxy({
                url: 'index.php?module=price&action=view&json=1', 
                method: 'POST'
            }),
            //baseParams:{task: "LISTING"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ 
        {name: 'id', type: 'int', mapping: 'id'},
        {name: 'article', type: 'string', mapping: 'article'},
        {name: 'description', type: 'string', mapping: 'description'},
        {name: 'groupID', type: 'int', mapping: 'groupID'},
        {name: 'suplyPrice', type: 'float', mapping: 'suplyPrice'},
        {name: 'suplyDiscount', type: 'int', mapping: 'suplyDiscount'},
        {name: 'suplyPriceRUB', type: 'float', mapping: 'suplyPriceRUB'},
		{name: 'discount', type: 'int', mapping: 'discount'},
        {name: 'price', type: 'float', mapping: 'price'},
        {name: 'currency', type: 'string', mapping: 'currency'},
		{name: 't50', type: 'float', mapping: 't50'},
		{name: 't60', type: 'float', mapping: 't60'},
		{name: 't70', type: 'float', mapping: 't70'},
		{name: 'P', type: 'int', mapping: 'P'},
		{name: 'I', type: 'int', mapping: 'I'},
		{name: 'width', type: 'int', mapping: 'width'},
		{name: 'height', type: 'int', mapping: 'height'},
		{name: 'deep', type: 'int', mapping: 'deep'},
		{name: 'length', type: 'int', mapping: 'length'},
		{name: 'partly', type: 'int', mapping: 'partly'},
		{name: 'intercenterlen', type: 'int', mapping: 'intercenterlen'},
		{name: 'weight', type: 'float', mapping: 'weight'},
		{name: 'companyID', type: 'int', mapping: 'companyID'},
		{name: 'companyName', type: 'string', mapping: 'companyName'},
		{name: 'groupName', type: 'string', mapping: 'groupName'}
      ]),
      sortInfo:{field: 'id', direction: "ASC"}
    });
	
  CompaniesDataStore = new Ext.data.Store({
      id: 'CompaniesDataStore',
      proxy: new Ext.data.HttpProxy({
                url: 'index.php?module=catalogue&action=viewcompanies&json=1', 
                method: 'POST'
            }),
            //baseParams:{task: "LISTING_COMPANY"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ 
        {name: 'id', type: 'int', mapping: 'id'},
        {name: 'name', type: 'string', mapping: 'name'},
        {name: 'description', type: 'string', mapping: 'description'}
      ]),
      sortInfo:{field: 'id', direction: "ASC"}
    });
  GroupDataStore = new Ext.data.Store({
      id: 'GroupDataStore',
      proxy: new Ext.data.HttpProxy({
                url: 'index.php?module=price&action=viewgroup&json=1', 
                method: 'POST'
            }),
            //baseParams:{task: "LISTING_COMPANY"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ 
        {name: 'id', type: 'int', mapping: 'id'},
        {name: 'name', type: 'string', mapping: 'name'},
        {name: 'description', type: 'string', mapping: 'description'}
      ]),
      sortInfo:{field: 'id', direction: "ASC"}
    });
    
  FullPriceColumnModel = new Ext.grid.ColumnModel(
    [{
        header: '#',
        readOnly: true,
        dataIndex: 'id',
        width: 40,
        hidden: false
      },{
        header: 'Артикул',
        dataIndex: 'article',
        width: 120,
        editor: new Ext.form.TextField({allowBlank: false,maxLength: 255})
      },{
        header: 'Описание',
        dataIndex: 'description',
        width: 180,
        editor: new Ext.form.TextField({allowBlank: true}),
      },{
        header: 'groupID',
        readOnly: true,
        dataIndex: 'groupID',
        width: 50,       
        hidden: true
      },{
          header: 'Группа',
          dataIndex: 'groupName',
          width: 150,
          editor: new Ext.form.ComboBox({
                 //typeAhead: true,
                 triggerAction: 'all',
                 store:GroupDataStore,
                 mode: 'remote',
                 displayField: 'name',
                 valueField: 'id',
                 lazyRender:true,
                 listClass: 'x-combo-list-small',
                 selectOnFocus:true
              })
      },{
        header: 'Розн.&euro;',
        dataIndex: 'suplyPrice',
        width: 40,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
      },{
        header: 'Скидка опт.',
        dataIndex: 'suplyDiscount',
        width: 50,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
	  },{
        header: 'Опт. руб.',
        readOnly: true,
        dataIndex: 'suplyPriceRUB',
        width: 40,
        hidden: false
      },{
        header: 'Скидка',
        dataIndex: 'discount',
        width: 50,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
      },{
        header: 'Цена',
        dataIndex: 'price',
        width: 50,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
      },{
        header: "Валюта",
        dataIndex: 'currency',
        width: 50
      },{
		header: "companyID",
        dataIndex: 'companyID',
        width: 70,
		hidden: true
	  },{
        header: 'Фабрика',
        dataIndex: 'companyName',
        width: 150,
        editor: new Ext.form.ComboBox({
               //typeAhead: true,
               triggerAction: 'all',
               store:CompaniesDataStore,
               mode: 'remote',
               displayField: 'name',
               valueField: 'id',
               lazyRender:true,
               listClass: 'x-combo-list-small',
			   selectOnFocus:true
            })
      },
	  { header: "&#x0394;T50", dataIndex: 't50', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})},
	  { header: "&#x0394;T60", dataIndex: 't60', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "&#x0394;T70", dataIndex: 't70', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Эл. мощ, Вт", dataIndex: 'P', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Ток, А", dataIndex: 'I', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Ширина, мм", dataIndex: 'width', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Высота, мм", dataIndex: 'height', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Глубина, мм", dataIndex: 'deep', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Длина, мм", dataIndex: 'length', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "partly", dataIndex: 'partly', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Межцентр., мм", dataIndex: 'intercenterlen', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Вес, кг", dataIndex: 'weight', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) }
	  ]
    );
    FullPriceColumnModel.defaultSortable= true;
    
   PresidentListingEditorGrid =  new Ext.grid.EditorGridPanel({
      id: 'PresidentListingEditorGrid',
      store: FullPriceDataStore,
      cm: FullPriceColumnModel,
      enableColLock:false,
      clicksToEdit:2,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
      bbar: new Ext.PagingToolbar({
                pageSize: 15,
                store: FullPriceDataStore,
                displayInfo: true
            }),
      tbar: [
          {
            text: 'Добавить',
            tooltip: 'Добавить новую запись',
            iconCls:'add',                      // reference to our css
            handler: displayFormWindow
          }, '-', { 
            text: 'Удалить запись',
            tooltip: 'Уделение выделенной записи',
            handler: confirmDeleteItem,   // Confirm before deleting
            iconCls:'remove'
          }, '-', /*{
            text: 'Поиск',
            tooltip: 'Расширенный поиск',
            handler: startAdvancedSearch,   
            iconCls:'search'
          }, '-',*/ new Ext.app.SearchField({
                    store: FullPriceDataStore,
                    params: {start: 0, limit: 15},
                    width: 120})
          ,'-', { 
              text: 'Обновить цены',
              tooltip: 'Обновить цены с учетом курса',
              handler: function() {RefreshPriceWindow.show();},
              iconCls:'add'
          }/*, { 
              text: 'Курс: ',
              tooltip: 'Изменить курс для розничных цен',
              handler: function() {RefreshPriceWindow.show();},
              iconCls:'add'
          }*/
      ]
    });
  PresidentListingEditorGrid.addListener('rowcontextmenu', onPresidentListingEditorGridContextMenu);

  PresidentListingContextMenu = new Ext.menu.Menu({
      id: 'PresidentListingEditorGridContextMenu',
      items: [
      { text: 'Modify this President', handler: modifyPresidentContextMenu },
      { text: 'Delete this President', handler: deletePresidentContextMenu },
      '-',
      { text: 'Print this grid', handler: printListingContextMenu }
      ]
   });    
    
  PresidentListingWindow = new Ext.Window({
      id: 'PresidentListingWindow',
      title: 'Прайс лист',
      closable:true,
      width:800,
      height:550,
      plain:true,
      layout: 'fit',
      items: PresidentListingEditorGrid
    });
  
  
  function onAddRecords(o,r,opt)
  {
  	  alert(o.reader.jsonData.results[0].article);
  	  o.reader.jsonData.results[0].article = 'rrrrr2';
  	  alert(o.reader.jsonData.results[0].article);
  }
  
  //FullPriceDataStore.on('load',onAddRecords );
  FullPriceDataStore.on('datachanged',onAddRecords );
  FullPriceDataStore.load({params: {start: 0, limit: 15}});
  //alert(FullPriceDataStore.reader.results);
  PresidentListingWindow.show();
  PresidentListingEditorGrid.on('afteredit', saveItem);
  
  ArticleField = new Ext.form.TextField({
    id: 'ArticleField',
    fieldLabel: 'Артикул',
    maxLength: 255,
    allowBlank: false,
    anchor : '95%',
    maskRe: /([a-zA-Z0-9\s]+)$/
      });
      
  DescriptionField = new Ext.form.TextField({
    id: 'DescriptionField',
    fieldLabel: 'Описание',
    //maxLength: 20,
    allowBlank: true,
    anchor : '95%',    
    maskRe: /([a-zA-Z0-9\s]+)$/  
      });
  
  EnteringOfficeField = new Ext.form.DateField({
    id:'EnteringOfficeField',
    fieldLabel: 'Entering Office',
    format : 'm/d/Y',
    allowBlank: false,
    anchor:'95%'
    });
    
  LeavingOfficeField = new Ext.form.DateField({
    id:'LeavingOfficeField',
    fieldLabel: 'Leaving Office',
    format : 'm/d/Y',
    allowBlank: false,
    anchor:'95%'
    });
  
  IncomeField = new Ext.form.NumberField({
    id:'IncomeField',
    fieldLabel: 'Income',
    allowNegative: false,
    allowBlank: false,
    anchor:'95%'
    });
  
  CompanyNameField = new Ext.form.ComboBox({
     id:'CompanyNameField',
     fieldLabel: 'Party',
     store: CompaniesDataStore,
     mode: 'remote',
     displayField: 'name',
     allowBlank: false,
     valueField: 'id',
     anchor:'95%',
     triggerAction: 'all'
      });
  
  CreateItemForm = new Ext.FormPanel({
        labelAlign: 'top',
        bodyStyle:'padding:5px',
        width: 600,        
        items: [{
            layout:'column',
            border:false,
            items:[{
                columnWidth:0.5,
                layout: 'form',
                border:false,
                items: [ArticleField, DescriptionField]
            },{
                columnWidth:0.5,
                layout: 'form',
                border:false,
                items: [CompanyNameField]
            }]
        }],
    buttons: [{
      text: 'Save and Close',
      handler: createItem
    },{
      text: 'Cancel',
      handler: function(){
        // because of the global vars, we can only instantiate one window... so let's just hide it.
        CreateItemWindow.hide();
      }
    }]
    });
  
  CreateItemWindow = new Ext.Window({
      id: 'CreateItemWindow',
      title: 'Новый товар',
      closable:true,
      width: 610,
      height: 250,
      plain:true,
      layout: 'fit',
      items: CreateItemForm
    });
});